package de.fhk.fst.dvr.helper

import java.io.InputStream
import java.util.List
import java.util.Properties

import org.apache.commons.net.ftp.FTPClient
import org.apache.commons.net.ftp.FTPFile
import org.apache.commons.net.ftp.FTPReply

import de.fhk.fst.dvr.recordings.DvrInterface
import de.fhk.fst.dvr.recordings.Recording

class RecordingFtpService implements DvrInterface {

  static transactional = true
  static connection = new FTPClient()

  def serviceMethod() {
  }

  @Override
  public boolean connect(Properties connectionProperties) {
    try {
      connection.connect connectionProperties.getAt("host")
      if (!FTPReply.isPositiveCompletion(connection.getReplyCode())) {
        disconnect()
        throw new IllegalStateException("FTP server refused connection.")
      }
    } catch (IOException e) {
      disconnect()
    }

    connection.enterLocalPassiveMode()
    if(!connection.login(connectionProperties.getAt("username"), connectionProperties.getAt("password"))) {
      disconnect()
      throw new IllegalArgumentException("user credentials are wrong.")
    }
    return connection.isConnected()
  }

  public boolean disconnect() {
    try {
      if (connection.isConnected()) {
        connection.disconnect()
      }
    } catch(IOException e) {
      return false
    }
    return true
  }

  @Override
  public boolean connect(String host, String username, String password) {
    Properties properties = new Properties()
    properties.putAt "host", host
    properties.putAt "username", username
    properties.putAt "password", password
    return connect(properties)
  }

  @Override
  public List<Recording> listRecordings() {
    def List<Recording> files = new ArrayList<Recording>()

    if (connect("localhost", "ftpuser", "ftpuser")) {
      def FTPFile[] remoteFiles = connection.listFiles()
      if (remoteFiles != null && remoteFiles.length > 0) {
        for (FTPFile remoteFile : remoteFiles) {
          files.add new Recording(remoteFile.getName(), remoteFile.getTimestamp().getTime())
        }
      }
      disconnect()
    }
    return files
  }

  @Override
  public InputStream streamVideo(String filename) {
    return null
  }
}
